const App = getApp();
const wxParse = require("../../wxParse/wxParse.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    item: [],
    join: [],
    isLoading: true,
    page: 1,
    no_more: false,

    contentTtext:false,//商品详情

    indicatorDots: true, // 是否显示面板指示点
    autoplay: true, // 是否自动切换
    interval: 3000, // 自动切换时间间隔
    duration: 800, // 滑动动画时长

    currentIndex: 1, // 轮播图指针
    floorstatus: false, // 返回顶部
    showView: true, // 显示商品规格

    // detail: {}, // 商品详情信息
    // goods_price: 0, // 商品价格
    // line_price: 0, // 划线价格
    // stock_num: 0, // 库存数量

    // goods_num: 1, // 商品数量
    // goods_sku_id: 0, // 规格id
    // cart_total_num: 0, // 购物车商品总数量
    // specData: {}, // 多规格信息

    // 分享按钮组件
    share: {
      show: false,
      cancelWithMask: true,
      cancelText: '关闭',
      actions: [
      //   {
      //   name: '生成商品海报',
      //   className: 'action-class',
      //   loading: false
      // }, 
      {
        name: '发送给朋友',
        openType: 'share'
      }],
      // 商品海报
      showPopup: false,
      
    },

    radio_type:1,
  },

  // 记录规格的数组
  //goods_spec_arr: [],

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(e) {
    let _this = this;
    this.setData({
      user_coupon_id: e.user_coupon_id ? e.user_coupon_id : 0,
      doing_id: e.doing_id ? e.doing_id : 0,
      coupon_id: e.coupon_id ? e.coupon_id : 0,
      status: e.status ? e.status : 'assign',
    });
    console.log(this.data.status);
    //根目录路径
    this.setData({
      app_root: App.root
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      isLoading: true,
      page: 1,
      no_more: false
    });
    this.getUserDetail();
    //优惠券详情
    this.getCouponDetail();
  },

  /**
   * 获取当前用户信息
   */
  getUserDetail: function () {
    let _this = this;
    App._get('user.index/detail', {}, function (result) {
      _this.setData({
        user_id: result.data.userInfo['user_id']
      });
    });
  },

  /**
   * 优惠券详情
   */
  getCouponDetail: function (isNextPage, page) {
    let _this = this;
    App._get('coupon/getCouponDetail', {
      page: page || 1,
      coupon_id: _this.data.coupon_id,
      doing_id: _this.data.doing_id,
      status: _this.data.status,
      status_type:_this.data.status
    }, function (result) {
      console.log(result);
      //当前商品 所有的拼团
      if (_this.data.status == 'assign'){
        _this.setData({
          join_team: result.data.doing_now
        });
      }
      let data = _this.initCouponsDetailData(result.data.list);
      console.log(data);
      //使用优惠券进入(有发起人，参与者)
      if (_this.data.status == 'allInit' ||
        _this.data.status == 'userInit' ||
        _this.data.status == 'userJoin' ||
        _this.data.status == 'userSelect' ||
        _this.data.status == 'userGather' ||
        _this.data.status == 'userPay' ||
        _this.data.status == 'status' ||
        _this.data.status == 'is_use'
      ) {
        console.log(result);
        if (isNextPage == true) {
          let dataList = _this.data.join;
          let num = _this.data.join_num + result.data.list.join.data.length;
          _this.setData({
            join: dataList.concat(result.data.list.join.data),
            last_page: result.data.list.join.last_page,
            join_num: num,
            isLoading: false,
          });
        } else {
          _this.setData({
            item: data,
            join: result.data.list.join.data,
            join_num: result.data.list.join.data.length,
            select_join: result.data.list.select_join,
            select_join_num: result.data.list.select_join.length,
            last_page: result.data.list.join.last_page,
            
            isLoading: false,
          });

        }
        //参与者高度
        _this.setSwiperHeight();
      } else {
        //优惠券列表（仅信息）
        _this.setData({
          item: data,
        });
      }
    });
  },

  /**
   * 初始化优惠券详情数据
   */
  initCouponsDetailData: function (data) {
    let _this = this;
    // 富文本转码
    if (data.coupon_assign_content &&  data.coupon_assign_content.length > 0) {
      wxParse.wxParse('content', 'html', data.coupon_assign_content, _this, 0);
    }

    // 富文本转码
    if (data.one_content && data.one_content.length > 0) {
      wxParse.wxParse('content1', 'html', data.one_content, _this, 0);
    }
    if (data.two_content && data.two_content.length > 0) {
      wxParse.wxParse('content2', 'html', data.two_content, _this, 0);
    }
    // 单规格商品封面图
    //data.image_path = data.coupon_assign_images[0]['images'];
    return data;
  },

  // 点击加载更多
  triggerDownLoad: function () {
    // 已经是最后一页
    if (this.data.page >= this.data.last_page) {
      this.setData({
        no_more: true
      });
      return false;
    }
    this.getCouponDetail(true, ++this.data.page);
  },

  //进入商店
  goToShop: function (e) {
    let shop_id = e.target.dataset.shop_id;
    //console.log(shop_id);
    wx.navigateTo({
      url: '/pages/shop/detail?shop_id=' + shop_id
    })
  },
  //立即领劵
  getCoupon: function (e) {
    let coupon_id = e.target.dataset.coupon_id;
    App._get('coupon/getCoupon', {
      coupon_id: coupon_id
    }, function (result) {
      //console.log(result);
      //App.showSuccess(result.msg);
      if (result.code == 1){
        wx.showModal({
          title: '提示',
          content: '请跳转【我的优惠券】去使用',
          success(res) {
            if (res.confirm) {
              //console.log('用户点击确定')
              wx.redirectTo({
                url: '/pages/user/coupon/coupon'
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    });
  },

  //使用优惠券（加入方式）
  radioChange:function(e){
    this.setData({
      radio_type: e.detail.value
    })

    if (e.detail.value == 2){
      wx.showModal({
        title: '友情提示',
        content: '此模式较难拼团成功（需自己找人），建议与朋友一起使用',
        showCancel: false,
        success: function (res) {
          // callback && (setTimeout(function() {
          //   callback();
          // }, 1500));
          //callback && callback();
        }
      });
    }
    

  },

  //使用优惠券
  useCoupon: function (e) {
    let coupon_id = this.data.coupon_id;
    let user_coupon_id = this.data.user_coupon_id;
    let radio_type = this.data.radio_type;
    let type = 'userInit';
    let status = this.data.status;
    
    let content = '';
    if (radio_type == 1) {
       type = 'userInit';
      content = '您确定要使用优惠券吗？';
    }
    if (radio_type == 2) {
       type = 'userSelect';
      content = '先支付10%的押金，凑满人数后再支付余款，您确定使用吗？';
    }
    // 订单创建成功后回调--微信支付
    let callback = function (result) {
      if (result.code === -10) {
        App.showError(result.msg, function () {
          // 跳转到未付款订单
          wx.redirectTo({
            url: '/pages/doing/user/index',
          });
        });
        return false;
      }
      // 发起微信支付
      wx.requestPayment({
        timeStamp: result.data.payment.timeStamp,
        nonceStr: result.data.payment.nonceStr,
        package: 'prepay_id=' + result.data.payment.prepay_id,
        signType: 'MD5',
        paySign: result.data.payment.paySign,
        success: function (res) {
          
          // 跳转到订单详情
          wx.redirectTo({
            //url: '../order/detail?order_id=' + result.data.order_id,
            url: '/pages/doing/user/index?type=' + type,
          });
        },
        fail: function () {
          App.showError('订单未支付', function () {
            // 跳转到未付款订单
            wx.redirectTo({
              url: '/pages/doing/user/index?type='+type,
            });
          });
        },
      });
    };

    wx.showModal({
      title: '提示',
      content: content,
      success(res) {
        if (res.confirm) {
          App._get('Doing/useCoupon', {
            coupon_id: coupon_id,
            user_coupon_id: user_coupon_id,
            status: status,
            radio_type: radio_type
          }, function (result) {
            //未登录
            if (result.data.code == 2) {
              App.showIsLogin(result.msg);
            }

            //console.log(result);
            if (result.code == 1 && radio_type == 1) {
              callback(result);
            }
            if (result.code == 1 && radio_type == 2) {
              callback(result);
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

  //放弃使用优惠券
  unUseCoupon: function () {
    let _this = this;
    let doing_id = this.data.doing_id;
    let coupon_id = this.data.coupon_id;

    wx.showModal({
      title: '提示',
      content: '您确定要取消发起吗？',
      success(res) {
        if (res.confirm) {
          App._get('Doing/unUseCoupon', {
            coupon_id: coupon_id,
            doing_id: doing_id
          }, function (result) {
            if (result.code == 1) {
              wx.navigateBack();
            }
          });
        } else if (res.cancel) {
          //console.log('用户点击取消')
        }
      }
    })

  },

  //报名加入
  joinCoupon: function (e) {
    let _this = this;
    let page = _this.data.page;
    let radio_type = e.target.dataset.radio_type;
    let type = 'userInit';
    //let coupon_id = this.data.item.contact_id;
    let coupon_id = e.target.dataset.coupon_id;
    //console.log(coupon_id);
    if (radio_type == 1) {
      type = 'userInit';
    }
    if (radio_type == 2) {
      type = 'userSelect';
    }

    // 订单创建成功后回调--微信支付
    let callback = function (result) {
      if (result.code === -10) {
        App.showError(result.msg, function () {
          // 跳转到未付款订单
          wx.redirectTo({
            url: '/pages/doing/user/index?type=' + type,
          });
        });
        return false;
      }
      // 发起微信支付
      wx.requestPayment({
        timeStamp: result.data.payment.timeStamp,
        nonceStr: result.data.payment.nonceStr,
        package: 'prepay_id=' + result.data.payment.prepay_id,
        signType: 'MD5',
        paySign: result.data.payment.paySign,
        success: function (res) {
          // 跳转到订单详情
          wx.redirectTo({
            //url: '../order/detail?order_id=' + result.data.order_id,
            url: '/pages/doing/user/index?type=' + type,
          });
        },
        fail: function () {
          App.showError('订单未支付', function () {
            // 跳转到未付款订单
            wx.redirectTo({
              url: '/pages/doing/user/index?type=' + type,
            });
          });
        },
      });
    };
    
    App._get('doing/joinDoingUser', {
      page: page || 1,
      doing_id: _this.data.doing_id,
      coupon_id: coupon_id
    }, function (result) {

      if (result.data.code == 2) {
        App.showIsLogin(result.msg, function () {
          wx.navigateBack();
        });
      }


      //console.log(result);
      if (result.data == 2){
        wx.showModal({
          title: '提示',
          content: '您已报名，是否跳转？',
          success(res) {
            if (res.confirm) {
              // 跳转到未付款订单
              wx.redirectTo({
                url: '/pages/doing/user/index?type=' + type,
              });
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        return false;
      }
      callback(result);
    });
    
  },

  //取消报名
  unJoinCoupon: function (e) {
    let doing_id = e.currentTarget.dataset.doing_id;
    let _this = this;
    let page = _this.data.page;

    wx.showModal({
      title: '提示',
      content: '您确定要取消报名吗？',
      success(res) {
        if (res.confirm) {
          App._get('doing/unJoinCouponUser', {
            page: page || 1,
            doing_id: doing_id
          }, function (result) {
            App.showSuccess(result.msg);
            _this.getCouponDetail();
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  /**
   * 设置swiper的高度
   */
  setSwiperHeight: function (isTap) {
    let join_num = this.data.join_num;
    // 获取系统信息(拿到屏幕宽度)
    let systemInfo = wx.getSystemInfoSync(),
      rpx = systemInfo.windowWidth / 750, // 计算rpx
      //tapHeight = isTap ? Math.floor(rpx * 82) : 0, // tap高度
      //peopleHeight = Math.floor(rpx * 65), // people高度
      tang = Math.floor(rpx * 210),
      more = Math.floor(rpx * 100),
      swiperHeight = tang * join_num + more; // swiper高度

    this.setData({
      swiperHeight
    });
  },

  //跳转 用户详情页
  goToDetail: function (e) {
    let user_id = e.currentTarget.dataset.user_id;
    wx.navigateTo({
      url: '/pages/social/detail?user_id=' + user_id
    })
  },

  //选择
  select: function (e) {
    let _this = this;
    let doing_user_id = e.currentTarget.dataset.doing_user_id;
    let key = e.currentTarget.dataset.key;
    App._get('doing/selectUser', {
      doing_user_id: doing_user_id,
      doing_id: _this.data.doing_id
    }, function (result) {
      //未登录
      if (result.data.code == 2) {
        App.showIsLogin(result.msg);
      }
      App.showSuccess(result.msg);
      let join_res = _this.data.join;
      for (let i = 0; i < join_res.length; i++) {
        if (i == key) {
          join_res[i].is_select = 1;
        }
      }
      _this.setData({
        join: join_res,
        select_join: result.data,
        select_join_num: result.data.length
      });
    });
  },

  //弃选
  unselect: function (e) {
    let _this = this;
    let doing_user_id = e.currentTarget.dataset.doing_user_id;
    let key = e.currentTarget.dataset.key;
    App._get('doing/unSelectUser', {
      doing_user_id: doing_user_id,
      doing_id: _this.data.doing_id
    }, function (result) {

      //未登录
      if (result.data.code == 2) {
        App.showIsLogin(result.msg);
      }

      App.showSuccess(result.msg);
      let join_res = _this.data.join;
      for (let i = 0; i < join_res.length; i++) {
        if (i == key) {
          join_res[i].is_select = 0;
        }
      }
      _this.setData({
        join: join_res,
        select_join: result.data,
        select_join_num: result.data.length
      });
    });
  },

 

  goToUserGather: function (e) {
    let _this = this;
    let doing_id = e.currentTarget.dataset.doing_id;
    console.log(doing_id);
    wx.showModal({
      title: '提示',
      content: '发起集合不可逆转，未被选中的用户将会被退回押金，您确定要发起集合吗？',
      success(res) {
        if (res.confirm) {
          App._get('doing/goToUserGather', {
            doing_id: doing_id
          }, function (result) {
            //console.log(result);
            wx.redirectTo({
              url: '/pages/doing/user/index?type=userGather'
            })
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /**
   * 获取商品信息
   */
  getGoodsDetail: function() {
    let _this = this;
    App._get('goods/detail', {
      goods_id: _this.data.goods_id
    }, function(result) {
      // 初始化商品详情数据
      let data = _this.initGoodsDetailData(result.data);
      _this.setData(data);
    });
  },

  /**
   * 初始化商品详情数据
   */
  initGoodsDetailData: function(data) {
    let _this = this;
    // 富文本转码
    if (data.detail.content.length > 0) {
      wxParse.wxParse('content', 'html', data.detail.content, _this, 0);
    }
    // 商品价格/划线价/库存
    // data.goods_sku_id = data.detail.sku[0].spec_sku_id;
    // data.goods_price = data.detail.sku[0].goods_price;
    // data.line_price = data.detail.sku[0].line_price;
    // data.stock_num = data.detail.sku[0].stock_num;
    // 单规格商品封面图
    data.image_path = data.detail.image[0]['file_path'];
    // 多规格商品封面图
    // if (data.detail.spec_type == 20 && data.detail.sku[0]['image']) {
    //   data.image_path = data.detail.sku[0]['image']['file_path'];
    // }
    // // 初始化商品多规格
    // if (data.detail.spec_type == 20) {
    //   data.specData = _this.initManySpecData(data.specData);
    // }
    return data;
  },

  /**
   * 初始化商品多规格
   */
  initManySpecData: function(data) {
    for (let i in data.spec_attr) {
      for (let j in data.spec_attr[i].spec_items) {
        if (j < 1) {
          data.spec_attr[i].spec_items[0].checked = true;
          this.goods_spec_arr[i] = data.spec_attr[i].spec_items[0].item_id;
        }
      }
    }
    return data;
  },

  /**
   * 点击切换不同规格
   */
  modelTap: function(e) {
    let attrIdx = e.currentTarget.dataset.attrIdx,
      itemIdx = e.currentTarget.dataset.itemIdx,
      specData = this.data.specData;
    for (let i in specData.spec_attr) {
      for (let j in specData.spec_attr[i].spec_items) {
        if (attrIdx == i) {
          specData.spec_attr[i].spec_items[j].checked = false;
          if (itemIdx == j) {
            specData.spec_attr[i].spec_items[itemIdx].checked = true;
            this.goods_spec_arr[i] = specData.spec_attr[i].spec_items[itemIdx].item_id;
          }
        }
      }
    }
    this.setData({
      specData
    });
    // 更新商品规格信息
    this.updateSpecGoods();
  },

  /**
   * 更新商品规格信息
   */
  updateSpecGoods: function() {
    let spec_sku_id = this.goods_spec_arr.join('_');

    // 查找skuItem
    let spec_list = this.data.specData.spec_list,
      skuItem = spec_list.find((val) => {
        return val.spec_sku_id == spec_sku_id;
      });

    // 记录goods_sku_id
    // 更新商品价格、划线价、库存
    if (typeof skuItem === 'object') {
      this.setData({
        goods_sku_id: skuItem.spec_sku_id,
        goods_price: skuItem.form.goods_price,
        line_price: skuItem.form.line_price,
        stock_num: skuItem.form.stock_num,
        image_path: skuItem.form.image_id > 0 ? skuItem.form.image_path : this.data.detail.image[0].file_path
      });
    }
  },

  /**
   * 设置轮播图当前指针 数字
   */
  setCurrent: function(e) {
    this.setData({
      currentIndex: e.detail.current + 1
    });
  },

  /**
   * 控制商品规格/数量的显示隐藏
   */
  onChangeShowState: function() {
    this.setData({
      showView: !this.data.showView
    });
  },

  /**
   * 返回顶部
   */
  goTop: function(t) {
    this.setData({
      scrollTop: 0
    });
  },

  /**
   * 显示/隐藏 返回顶部按钮
   */
  scroll: function(e) {
    this.setData({
      floorstatus: e.detail.scrollTop > 200
    })
  },

  /**
   * 增加商品数量
   */
  up: function() {
    this.setData({
      goods_num: ++this.data.goods_num
    })
  },

  /**
   * 减少商品数量
   */
  down: function() {
    if (this.data.goods_num > 1) {
      this.setData({
        goods_num: --this.data.goods_num
      });
    }
  },

  /**
   * 跳转购物车页面
   */
  flowCart: function() {
    wx.switchTab({
      url: "../flow/index"
    });
  },

  /**
   * 加入购物车and立即购买
   */
  submit: function(e) {
    let _this = this,
      submitType = e.currentTarget.dataset.type;
    if (submitType === 'buyNow') {
      // 立即购买
      wx.navigateTo({
        url: '../flow/checkout?' + App.urlEncode({
          order_type: 'buyNow',
          goods_id: _this.data.goods_id,
          goods_num: _this.data.goods_num,
          goods_sku_id: _this.data.goods_sku_id
        }),
        success() {
          // 关闭弹窗
          _this.onToggleTrade();
        }
      });
    } else if (submitType === 'addCart') {
      // 加入购物车
      App._post_form('cart/add', {
        goods_id: _this.data.goods_id,
        goods_num: _this.data.goods_num,
        goods_sku_id: _this.data.goods_sku_id,
      }, function(result) {
        App.showSuccess(result.msg);
        _this.setData(result.data);
      });
    }
  },

  /**
   * 浏览商品图片
   */
  previewImages: function(e) {
    let index = e.currentTarget.dataset.index,
      imageUrls = [];
    this.data.detail.image.forEach(function(item) {
      imageUrls.push(item.file_path);
    });
    wx.previewImage({
      current: imageUrls[index],
      urls: imageUrls
    })
  },

  /**
   * 预览Sku规格图片
   */
  previewSkuImage: function(e) {
    wx.previewImage({
      current: this.data.image_path,
      urls: [this.data.image_path]
    })
  },

  /**
   * 跳转到评论
   */
  navigateToComment: function() {
    wx.navigateTo({
      url: './comment/comment?goods_id=' + this.data.goods_id
    })
  },

  /**
   * 分享当前页面
   */
  onShareAppMessage: function() {
    // 构建页面参数
    let params = App.urlEncode({
      'goods_id': this.data.goods_id,
      'referee_id': App.getUserId()
    });
    return {
      title: this.data.detail.goods_name,
      desc: "",
      path: "/pages/goods/index?" + params
    };
  },

  /**
   * 显示分享选项
   */
  openActionsheet(e) {
    // 记录formId
    App.saveFormId(e.detail.formId);
    this.setData({
      'share.show': true
    });
  },

  /**
   * 关闭分享选项
   */
  closeActionSheet() {
    this.setData({
      'share.show': false
    });
  },

  /**
   * 点击分享选项
   */
  clickAction(e) {
    // if (e.detail.index === 0) {
    //   // 显示商品海报
    //   this.showPoster();
    // }
    this.closeActionSheet();
  },

  /**
   * 切换商品海报
   */
  togglePopup() {
    this.setData({
      'share.showPopup': !this.data.share.showPopup
    });
  },

  /**
   * 显示商品海报图
   */
  showPoster: function() {
    let _this = this;
    wx.showLoading({
      title: '加载中',
    });
    App._get('goods/poster', {
      goods_id: _this.data.goods_id
    }, function(result) {
      _this.setData(result.data, function() {
        _this.togglePopup();
      });
    }, null, function() {
      wx.hideLoading();
    });
  },

  /**
   * 保存海报图片
   */
  savePoster: function(e) {
    let _this = this;
    // 记录formId
    App.saveFormId(e.detail.formId);
    wx.showLoading({
      title: '加载中',
    });
    // 下载海报图片
    wx.downloadFile({
      url: _this.data.qrcode,
      success: function(res) {
        wx.hideLoading();
        // 图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function(data) {
            wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000
            });
            // 关闭商品海报
            _this.togglePopup();
          },
          fail: function(err) {
            if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
              wx.showToast({
                title: "请允许访问相册后重试",
                icon: "none",
                duration: 1000
              });
              setTimeout(function() {
                wx.openSetting();
              }, 1000);
            }
          },
          complete(res) {
            console.log('complete');
            // wx.hideLoading();
          }
        })
      }
    })
  },

  /**
   * 确认购买弹窗
   */
  onToggleTrade(e) {
    if (typeof e === 'object') {
      // 记录formId
      e.detail.hasOwnProperty('formId') && App.saveFormId(e.detail.formId);
    }
    this.setData({
      showBottomPopup: !this.data.showBottomPopup
    });
  },
  // 点击详情页 展开/搜索
  clickcontent:function(){
    
    if (this.data.contentTtext == false){
      this.setData({
        contentTtext: true
      });
    }else{
      this.setData({
        contentTtext: false
      });
    }
  },
  //取消报名加入
  uncancel:function(e){
    let _this = this;
    let doing_user_id = e.currentTarget.dataset.doing_user_id;
    let key = e.currentTarget.dataset.key;
    wx.showModal({
      title: '提示',
      content: '您确定要取消报名吗？',
      success(res) {
        if (res.confirm) {
          App._get('doing/uncancel', {
            doing_user_id: doing_user_id,
            doing_id: _this.data.doing_id
          }, function (result) {
              //console.log(result);

            // if (result.code == 1) {
            //   wx.navigateBack()
            // }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  goBack:function(){
    wx.navigateBack();
  },
})